package com.faithbj.controller.secondVerifySelect;

import com.faithbj.common.configuration.Pager;
import com.faithbj.common.web.controller.BaseController;
import com.faithbj.process.ProcessApplicationService;
import com.faithbj.process.State;
import com.faithbj.process.TaskModel;
import com.faithbj.utils.RandomUtils;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/secondVerifySelect")
public class SecondVerifySelectController extends BaseController {

	private static final long serialVersionUID = -8756186395374983872L;

    @Autowired
    private ProcessApplicationService processApplicationService;
	
	@RequestMapping("/index")
	public String list(Pager pager, ModelMap model) {
        List<TaskModel> tasks = processApplicationService.listAvailableTasksWithContentByUserAndState(
                State.SECOND_CHECK_SELECT, pager.getFirstResult(), pager.getPageCount());
        pager.setTotalCount(processApplicationService.countAvailableTasksByUserAndState(State.SECOND_CHECK_SELECT));
        pager.setResult(tasks);
		model.put("pager", pager);
		return "/secondVerifySelect/list";
    }

    @RequestMapping("/sendCheck")
    public String sendCheck(ModelMap model) {
        List<TaskModel> tasks = processApplicationService.listAvailableTasksWithContentByUserAndState(
                State.SECOND_CHECK_SELECT, 0, Integer.MAX_VALUE);
        List<Long> allIds = Lists.transform(tasks, new Function<TaskModel, Long>() {
            @Override
            public Long apply(TaskModel task) {
                return task.getId();
            }
        });
        List<Long> selectedIds = RandomUtils.selectPercentN(allIds, 20); // 抽查20%
        List<TaskModel> selectedTasks = Lists.newArrayList();
        int limit = 20;
        boolean exceeded = false;
        for (TaskModel t : tasks) {
            if (selectedTasks.size() >= limit) {
                exceeded = true;
                break;
            }
            Map<String, Object> output = Maps.newHashMap();
            long id = t.getId();
            boolean check2Selected = selectedIds.contains(id);
            output.put("check2Checked", true);
            output.put("check2Selected", check2Selected);
            processApplicationService.claimAndGroupStartTask(id);
            processApplicationService.completeGroupTask(id, t.getCheckTotal(), output);
            selectedTasks.add(t);
        }
        model.put("data", selectedTasks);
        model.put("exceeded", exceeded);
        return "/secondVerifySelect/result";
    }
}
